const express=require("express");
const mysql=require("mysql");
const ejs=require("ejs");
const moment=require("moment");

var app=express();
app.set("view engine","ejs");
app.use(express.static("./public"));

var pool  = mysql.createPool({
    connectionLimit : 15,
    host            : 'localhost',
    user            : 'root',
    password        : '123456',
    database        : 'hotevent'
  });

  let page=1;
  let total=3;

app.get("/index",function(req,res){

  pool.getConnection(function(err, connection) {

      if (err) throw err; 

      let sql="select * from hotevents order by searchsum desc "
     
      connection.query(sql, function (error, results, fields) {
       
        connection.release();
     
        if (error) throw error;
     
         total=results.length;
      });
    });

    
    pool.getConnection(function(err, connection) {
      
      if( total<3) total=3;
    
      if (err) throw err; 
       
      let sql="select * from hotevents where 1=1 "
    
      let str='';
      str+=req.query.keyword;
      let params=["%"+str+"%"];

      if(req.query.keyword){
        sql+="and keyword like ? "
      }

      let pageSize=3;

      if(req.query.page){
        page=1;
      }

      if(req.query.prepage=="pre"){
        page=page-1
      }

      if(req.query.nextpage=="next"){
        page=page+1
      }

      if(page<1) page=1;

      if(req.query.last){
        page=Math.ceil(total/3)
      }

      if(page>Math.ceil(total/3)){
        page=Math.ceil(total/3)
      }

      let start=(page-1)*pageSize;

      sql+="ORDER BY searchsum DESC "+"limit " + start +"," + pageSize;

      connection.query(sql, params,function (error, results, fields) {
         
          connection.release();
       
          if (error) throw error;
       
            res.render("index",{
                res:results,
                moment:moment,
                pages:{
                  page:page,
                  zong:Math.ceil(total/3)
                }
            })
        });
      });

})

app.get("/detail",function(req,res){

  let id=req.query.id;

  pool.getConnection(function(err, connection) {
      if (err) throw err; 
     
      let sql="select * from hotevents where id=? ";
      let params=[id];

      connection.query(sql, params,function (error, results, fields) {
       
        connection.release();
     
      
        if (error) throw error;

        res.render("details",{
            id:results,
            moment:moment
        })

      });
    });

})

var http=require("http");
var server=http.createServer(app);
var io=require("socket.io").listen(server);

io.on("connection",function(socket){
  socket.on("chat",function(msg){
      io.emit("back",msg);
  })
})


  server.listen(7000,(req,res)=>{
    console.log("开始服务成功")
  })